// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package save

import (
	"context"
	"fmt"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/config"
	"server/app/errs"
	"server/app/http/logics/master/setting/pond"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
	"strings"
)

// Logic
// 保存鱼塘.
type Logic struct {
	pond.Logic

	admin  *models.ArcadeAdmins
	arcade *models.Arcades

	affects     int64
	kind        kind.ArcadeAdminOperation
	kindContent string
	pond        *models.ArcadePond

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// After
// 后置日志.
func (o *Logic) After(ctx context.Context, _ iris.Context, _ result.Result) {
	if o.affects > 0 {
		_, _ = services.NewArcadeLogsService().Add(ctx,
			o.arcade, o.admin, o.kind, o.kindContent,
		)
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)

	// 1. 事务处理.
	if err = db.Transaction(ctx,
		o.RunCheck,
		o.RunSave,
		o.RunStatistic,
	); err != nil {
		return res.WithError(err)
	}

	// 2. 保存完成.
	o.response.Id = o.pond.Id
	o.response.Name = o.pond.Name
	return res.With(o.response)
}

// RunCheck
// 查询数据.
func (o *Logic) RunCheck(ctx context.Context, sess *db.Session) (err error) {
	var (
		has   bool
		total int64
	)

	// 1. 新增模式.
	if o.request.Id == 0 {
		// 1.1 鱼塘总数.
		if total, err = o.CalcTotal(sess, o.arcade.Id); err != nil {
			return
		}

		// 1.2 鱼塘限量.
		if int(total) >= config.Arcade.GetPondCount() {
			err = errs.ErrArcadePondMaxLimited
		}
	} else {
		// 2. 编辑模式.
		if o.pond, has, err = services.NewArcadePondService(sess).Dao.GetById(ctx, o.request.Id); err != nil {
			err = errs.ErrDatabaseQuery
		} else if !has || o.pond.ArcadeId != o.arcade.Id {
			err = errs.ErrArcadeSwiperNotFound
		}
	}
	return
}

// RunSave
// 保存鱼塘.
//
// 添加或编辑模式分发.
func (o *Logic) RunSave(ctx context.Context, sess *db.Session) (err error) {
	if o.pond != nil {
		return o.RunSaveToUpdate(ctx, sess)
	}
	return o.RunSaveToCreate(ctx, sess)
}

// RunSaveToCreate
// 新增鱼塘.
func (o *Logic) RunSaveToCreate(ctx context.Context, sess *db.Session) (err error) {
	var service = services.NewArcadePondService(sess)

	if o.pond, err = service.Dao.AddByStruct(ctx, &models.ArcadePond{
		ArcadeId: o.arcade.Id,
		Deleted:  kind.DeletedNo,
		Enabled:  o.request.Enabled,
		Kind:     o.request.Kind,
		Area:     o.request.Area,
		Depth:    o.request.Depth,
		Seat:     o.request.Seat,
		Name:     o.request.Name,
	}); err != nil {
		err = errs.ErrDatabaseQuery
	} else {
		if _, err = service.Dao.UpdateFieldsById(ctx, map[string]any{
			"deleted": kind.DeletedNo,
		}, o.pond.Id); err != nil {
			err = errs.ErrDatabaseQuery
		}
	}

	if err == nil {
		o.affects = 1
		o.RunSaveToCreateLog()
	}
	return
}

func (o *Logic) RunSaveToCreateLog() {
	var changes = []string{
		fmt.Sprintf(`状态为[%s]`, o.request.Enabled.Text()),
		fmt.Sprintf(`类型为[%s]`, o.request.Kind.Text()),
		fmt.Sprintf(`钓位为[%s]`, o.request.Seat.Text()),
		fmt.Sprintf(`面积为[%v]`, o.request.Area),
		fmt.Sprintf(`水深为[%v]`, o.request.Depth),
	}

	// 1. 日志内容.
	o.kind = kind.ArcadeAdminOperationPondCreate
	o.kindContent = o.kind.ToPondCreate(o.pond.Name, strings.Join(changes, ", "))
}

// RunSaveToUpdate
// 编辑鱼塘.
func (o *Logic) RunSaveToUpdate(ctx context.Context, sess *db.Session) (err error) {
	if o.affects, err = services.NewArcadePondService(sess).Dao.UpdateFieldsById(ctx, map[string]any{
		"enabled": o.request.Enabled,
		"kind":    o.request.Kind,
		"area":    o.request.Area,
		"depth":   o.request.Depth,
		"seat":    o.request.Seat,
		"name":    o.request.Name,
	}, o.pond.Id); err != nil {
		err = errs.ErrDatabaseQuery
	} else if o.affects > 0 {
		o.RunSaveToUpdateLog()
	}
	return
}

func (o *Logic) RunSaveToUpdateLog() {
	var changes = make([]string, 0)

	// 1. 名称变更.
	if o.pond.Name != o.request.Name {
		changes = append(changes,
			fmt.Sprintf(`名称从[%s]改为[%s]`, o.pond.Name, o.request.Name),
		)
	}

	// 2. 状态变更.
	if o.pond.Enabled != o.request.Enabled {
		changes = append(changes,
			fmt.Sprintf(`状态从[%s]改为[%s]`, o.pond.Enabled.Text(), o.request.Enabled.Text()),
		)
	}

	// 3. 类型变更.
	if o.pond.Kind != o.request.Kind {
		changes = append(changes,
			fmt.Sprintf(`类型从[%s]改为[%s]`, o.pond.Kind.Text(), o.request.Kind.Text()),
		)
	}

	// 4. 钓位变更.
	if o.pond.Seat != o.request.Seat {
		changes = append(changes,
			fmt.Sprintf(`钓位从[%s]改为[%s]`, o.pond.Seat.Text(), o.request.Seat.Text()),
		)
	}

	// 5. 面积变更.
	if o.pond.Area != o.request.Area {
		changes = append(changes,
			fmt.Sprintf(`面积从[%v]改为[%v]`, o.pond.Area, o.request.Area),
		)
	}

	// 6. 水深变更.
	if o.pond.Depth != o.request.Depth {
		changes = append(changes,
			fmt.Sprintf(`水深从[%v]改为[%v]`, o.pond.Depth, o.request.Depth),
		)
	}

	// 7. 日志内容.
	o.kind = kind.ArcadeAdminOperationPondUpdate
	o.kindContent = o.kind.ToPondUpdate(o.pond.Name, strings.Join(changes, ", "))
}

// RunStatistic
// 重建统计.
func (o *Logic) RunStatistic(_ context.Context, sess *db.Session) (err error) {
	if o.response.PondTotal, err = o.CalcTotal(sess, o.arcade.Id); err == nil {
		if o.response.PondCount, err = o.CalcEnables(sess, o.arcade.Id); err == nil {
			if err = o.CalcUpdate(sess, o.arcade.Id, o.response.PondTotal, o.response.PondCount); err == nil {
				o.response.Name = o.pond.Name
			}
		}
	}
	return
}
